/**
 * 
 */
package com.tju.worker;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <p>
 * a pool to control threads
 * </p>
 * 
 */
public class WorkerQueue {

	/**
	 * <p>
	 * pool
	 * </p>
	 */
	private Queue<Worker> pool;

	/**
	 * <p>
	 * maxCapacity
	 * </p>
	 */
	private final int maxCapacity;
	/**
	 * <p>
	 * default maximum number of threads 
	 *</p>
	 */
	private static final int DEFAULT_MAX_CAPACITY = 20;

	
	public WorkerQueue() {
		this(DEFAULT_MAX_CAPACITY);
	}

	public WorkerQueue(int maxCapacity) {
		this.maxCapacity = maxCapacity;
		pool = new LinkedList<Worker>();
	}
	
	
	/**
	 * 
	 */
	public synchronized void executeTasks() {
		Worker worker;
		while ((worker = pollWorker()) != null) {
			worker.start();
		}
	}

	/**
	 * 
	 */
	private synchronized void waitForInstructions() {
			try {
				wait();
			} catch (InterruptedException ie) {
				// ie.printStackTrace();
			}
	}

	public synchronized Worker pollWorker() {
		while (pool.size() == 0) {
			waitForInstructions();
		}
		return pool.poll();
	}

	public synchronized void enqueueWorker(Worker worker) {
		if (!checkCapacity()) {
			System.out.println("waiting ...");
			waitForInstructions();
		}
		pool.add(worker);
		worker.sendSignal();
	}

	public synchronized void destroy() {
		notifyAll();
		pool.clear();
	}

	private boolean checkCapacity() {
		return pool.size() < maxCapacity;
	}

}
